package com.jbl.st.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbl.commonutils.MD5;
import com.jbl.exceptionhandler.ManagerException;
import com.jbl.st.entity.Student;
import com.jbl.st.entity.StudentInfo;
import com.jbl.st.service.StudentInfoService;
import com.jbl.st.service.StudentService;
import com.jbl.te.entity.Department;
import com.jbl.te.entity.Departmentclass;
import com.jbl.te.entity.Major;
import com.jbl.te.entity.User;
import com.jbl.te.service.DepartmentService;
import com.jbl.te.service.DepartmentclassService;
import com.jbl.te.service.MajorService;
import com.jbl.te.service.UserService;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ExcelStudentListener extends AnalysisEventListener<StudentData> {

    private StudentService studentService;
    private StudentInfoService infoService;
    private UserService userService;
    private DepartmentService departmentService;
    private MajorService majorService;
    private DepartmentclassService classService;


    public ExcelStudentListener(
            StudentService studentService,
            StudentInfoService infoService,
            DepartmentService departmentService,
            MajorService majorService,
            DepartmentclassService classService,
            UserService userService

    ) {
        this.studentService = studentService;
        this.departmentService = departmentService;
        this.majorService = majorService;
        this.classService = classService;
        this.infoService = infoService;
        this.userService = userService;
    }

    @Transactional
    @Override
    public void invoke(StudentData studentData, AnalysisContext analysisContext) {
        if(studentData == null) {
            throw new ManagerException(20001,"添加失败");
        }

        try {
            boolean gender = studentData.getGender() != 0;
            //校验系，专业，行政班  身份证号
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.eq("name",studentData.getDepartmentName());
            Department department = departmentService.getOne(departmentQueryWrapper);
            if(department == null) throw new ManagerException(20001,"所属系不存在！");

            QueryWrapper<Major> majorQueryWrapper = new QueryWrapper<>();
            majorQueryWrapper.eq("name",studentData.getMajorName());
            Major major = majorService.getOne(majorQueryWrapper);
            if(major == null) throw new ManagerException(20001,"所属专业不存在！");

            QueryWrapper<Departmentclass> departmentclassQueryWrapper = new QueryWrapper<>();
            departmentclassQueryWrapper.eq("name",studentData.getDepartmentclassName());
            Departmentclass departmentclass = classService.getOne(departmentclassQueryWrapper);
            if(departmentclass == null) throw new ManagerException(20001,"所属行政班不存在！");

            //添加学生
            Student student = new Student();
            StudentInfo info = new StudentInfo();
            student.setCollegeId(department.getCollegeId());
            student.setDepartmentId(department.getId());
            student.setMajorId(major.getId());
            student.setDepartmentclassId(departmentclass.getId());
            info.setGender(gender); info.setName(studentData.getName()); info.setIdentityNumber(studentData.getIdentityNumber());

            //生成学号
            StringBuilder number = new StringBuilder(); //拼接学号

            SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd");//日期格式
            number.append(sformat.format(new Date()).substring(2,4)); //入职年份后2位
            //系序号，2位
            departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.orderByAsc("gmt_create");
            List<Department> departmentList = departmentService.list(departmentQueryWrapper);
            for (Integer i = 0;i < departmentList.size();i++) {
                if(departmentList.get(i).getId().equals(student.getDepartmentId())) {
                    if(i < 10) {
                        number.append("0");
                    } number.append(i.toString());
                }
            }
            //专业序号，2位
            majorQueryWrapper = new QueryWrapper<>();
            majorQueryWrapper.orderByAsc("gmt_create");
            List<Major> majorList = majorService.list(majorQueryWrapper);
            for (Integer i = 0;i < majorList.size();i++) {
                if(majorList.get(i).getId().equals(student.getMajorId())) {
                    if(i < 10) {
                        number.append("0");
                    } number.append(i.toString());
                }
            }
            //行政班序号，2位
            departmentclassQueryWrapper = new QueryWrapper<>();
            departmentclassQueryWrapper.orderByAsc("gmt_create");
            List<Departmentclass> departmentclassList = classService.list(departmentclassQueryWrapper);
            for (Integer i = 0;i < departmentclassList.size();i++) {
                if(departmentclassList.get(i).getId().equals(student.getDepartmentclassId())) {
                    if(i < 10) {
                        number.append("0");
                    } number.append(i.toString());
                }
            }
            //学生序号，3位
            QueryWrapper<Student> wrapper = new QueryWrapper<>();
            wrapper.eq("departmentclass_id",student.getDepartmentclassId());
            student.setOrderNumber(studentService.count(wrapper)+1);
            Integer count = student.getOrderNumber();
            if (count < 10) number.append("0");
            number.append(count.toString());

            student.setStudentNumber(number.toString());

            boolean save = studentService.save(student);
            if(!save) throw new ManagerException(20001,"添加学生失败！");
            info.setId(student.getId());
            infoService.save(info);

            //添加学生对应的用户
            User user = new User();
            user.setId(student.getId());
            user.setName("学生");
            user.setRole("student");
            user.setUsername(student.getStudentNumber()); //账号为学号
            String psd = info.getIdentityNumber().substring(info.getIdentityNumber().length()-8);
            user.setPassword(MD5.encrypt(psd)); //密码为身份证后8位（加密）

            boolean save1 = userService.save(user);
            if(!save1) throw new ManagerException(20001,"添加用户失败！");
        } catch (Exception e) {
            System.out.println("&&&&&&&&&&&&&&&&&&&&&&");
            throw new ManagerException(20001,"中途有学生添加失败！");
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
